package com.kuaimacode.kframework.agent.controller.notice;

import com.github.pagehelper.PageInfo;
import com.kuaimacode.kframework.agent.services.notice.NoticeService;
import com.kuaimacode.kframework.agent.util.SessionUtil;
import com.kuaimacode.kframework.common.Constant;
import com.kuaimacode.kframework.common.JsonResult;
import com.kuaimacode.kframework.constants.PageConstants;
import com.kuaimacode.kframework.mybatis.models.index.Notice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

/**
 * @author anzy
 * @date 2019/06/12
 */

/**
 * Controller
 */
@Controller
@RequestMapping({"/notice"})
public class NoticeController {
	private static String PAGE_FILE_NAME = "notice/";

	@Autowired
	private NoticeService noticeServices;


	@RequestMapping(value = {"/index"})
	public String index(@RequestParam(value = "pageNum", required = true, defaultValue = PageConstants.PAGE_NUM+"") int pageNum,
										@RequestParam(value = "pageSize", required = true, defaultValue = PageConstants.PAGE_SIZE+"") int pageSize,
						ModelMap model) {
		PageInfo<Notice> pageInfo = noticeServices.findAll(pageNum, pageSize);
		// pageInfo.list notice
		model.put("pageInfo", pageInfo);
		return PAGE_FILE_NAME + "index";
	}


	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(ModelMap map) {
		Notice notice = new Notice();
		map.put("notice", notice);
		map.put("isAdd", true);
		return PAGE_FILE_NAME+"form";
	}

	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public String edit(@PathVariable String id, ModelMap map) {
		Notice notice = noticeServices.getById(id);
		map.put("notice", notice);
		map.put("isAdd", false);
		return PAGE_FILE_NAME+"form";
	}

	@RequestMapping(value = {"/edit"}, method = RequestMethod.POST)
	@ResponseBody
	public JsonResult edit(Notice notice, Boolean isAdd,ModelMap map) {
		try {
			if(isAdd){
				// 新建保存
				notice.setCreateBy(SessionUtil.getUserId());
				notice.setAgentId(SessionUtil.getAgentId());
				noticeServices.save(notice);
			}else{
				// 编辑保存
				noticeServices.updateById(notice);
			}
		} catch (Exception e) {
			return JsonResult.failure(e.getMessage());
		}
		return JsonResult.success();
	}


	@RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
	public String detail(@PathVariable String id, ModelMap map) {
		Notice notice = noticeServices.getById(id);
		map.put("notice", notice);
		return PAGE_FILE_NAME+"detail";
	}


	@ResponseBody
	@PostMapping("/delete/{id}")
	public JsonResult delete(@PathVariable String id, ModelMap map) {
		try {
			noticeServices.removeById(id);
		} catch (Exception e) {
			return JsonResult.failure(e.getMessage());
		}
		return JsonResult.success();
	}


}
